// 公共的导航slice
import { createSlice } from '@reduxjs/toolkit'
import { useSelector } from 'react-redux'

export type TPanes = {
    title: string
    key: string
    closable: boolean
}
// type TCommonState = {
//     panes: TPanes[]
// }

const initialState = {
    panes: [
        {
            title: '首页',
            key: '/',
            closable: false // 不可关闭
        }
    ]
}

const siderCommonSlice = createSlice({
    name: 'siderCommon',
    initialState,
    reducers: {
        // 添加tab
        addPanes(state, action) {
            const { key } = action.payload
            const isExist: TPanes = state.panes.find((v: TPanes) => v.key === key) as TPanes
            if (!isExist) {
                state.panes.push(action.payload)
            }
        },
        // 删除tab,根据下标删除
        removePanes(state, action) {
            state.panes.splice(action.payload, 1)
        },
        // 修改tab名称,根据key修改
        updatePanes(state, action) {
            const info: TPanes = state.panes.find((v) => v.key === action.payload.key) as TPanes
            info.title = action.payload.title
        },
        // 删除tab,根据key删除
        removePanesByKey(state, action) {
            const index = state.panes.findIndex((v) => v.key === action.payload)
            state.panes.splice(index, 1)
        }
    }
})

// 导出action
export const { addPanes, removePanes, updatePanes, removePanesByKey } = siderCommonSlice.actions

// 导出状态
export const useSelectorsiderCommon = () => useSelector((state: any) => state.siderCommon)

// 导出reducer
export default siderCommonSlice.reducer
